google.maps.event.addDomListener(window, "load", initialize);
function initialize() {
	//mapCanvas.setMapTypeId(google.maps.MapTypeId.ROADMAP);
  	//Creates a infowindow object.
  	infoWnd = new google.maps.InfoWindow();
    var geocoder = new google.maps.Geocoder();
  	if (geocoder && navigator.geolocation){
		navigator.geolocation.getCurrentPosition(showPosition);//, geoLocError, geoLocProgress, {desiredAccuracy:5, maxWait:15000,enableHighAccuracy: true,timeout:15000,maximumAge: Infinity});
	}
  	
}

function rad2deg(angle) {
  return angle * 57.29577951308232; // angle / Math.PI * 180
}

function deg2rad(angle) {
  return angle * .017453292519943295; // (angle / 180) * Math.PI;
}

function getReverseGeocodingData(lat, lng) {
    var latlng = new google.maps.LatLng(lat, lng);
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({ 'latLng': latlng }, function (results, status) {
        if (status !== google.maps.GeocoderStatus.OK) {
        	alert(status);
        }
        // This is checking to see if the Geoeode Status is OK before proceeding
        if (status == google.maps.GeocoderStatus.OK) {
        	var address = (results[0].formatted_address);
        	console.log('You are near here address: ' + address)
    	}
	});
}

function showPosition(position){
	var lat = position.coords.latitude;
	var lng = position.coords.longitude;
    var latLng = [lat, lng];
    showMaps(lat, lng);    
}
var total_groups = 0;
function showMaps(lat, lng){
	document.getElementById('loading').style.display = 'block';
	var R = 6371;
    var r = 10; //km
    var max_lat = lat + rad2deg(r/R);
    var min_lat = lat - rad2deg(r/R);
    var max_lng = lng + rad2deg(r/R/Math.cos(deg2rad(lat)));
	var min_lng = lng - rad2deg(r/R/Math.cos(deg2rad(lat)));

	var xmlhttp;
	if (window.XMLHttpRequest){
		// code for IE7+, Firefox, Chrome, Opera, Safari
	  	xmlhttp = new XMLHttpRequest();
	}else{
		// code for IE6, IE5
	  	xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.open("POST","site/maps",true);
	//xmlhttp.setRequestHeader("Content-Type", "text/plain");
	xmlhttp.onreadystatechange=function(){
		document.getElementById('loading').style.display = 'none';
	  	if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
	  		var stationList = xmlhttp.responseText;
	  		stationList = JSON.parse(stationList);
	  		var maxzoom = 14;
	  		if(stationList.length > 0){
		  		total_groups = stationList.length
		  		if(stationList.length > 10)
		  		{
		  			maxzoom = 12
		  		}
		    	var myOptions = {
			      //zoom: 12,
			      scaleControl: true,
			      maxZoom: maxzoom,
			      center: new google.maps.LatLng(lat, lng),
			      mapTypeId: google.maps.MapTypeId.ROADMAP
			    }
				var mapDiv = document.getElementById("map_canvas");
				mapCanvas = new google.maps.Map(mapDiv, myOptions);
				var bounds = new google.maps.LatLngBounds();
			    var station, i, latlng;
				for (i in stationList) {
					station = stationList[i];
					latlng = new google.maps.LatLng(station.latlng[0], station.latlng[1]);
					bounds.extend(latlng);
					var marker = createMarker(
						    mapCanvas, 
						    latlng, 
						    station.title,
						    station.description,
						    station.photo,
						    station.date,
						    station.address
						);    
						//Creates a sidebar button for the marker
						createMarkerButton(marker);
				}
				//Fits the map bounds
			  	mapCanvas.fitBounds(bounds);
			  	var boxCoords = [
			            new google.maps.LatLng(min_lat, min_lng),
			            new google.maps.LatLng(max_lat, min_lng),
			            new google.maps.LatLng(max_lat, max_lng),
			            new google.maps.LatLng(min_lat, max_lng)
			    ];
			    /*
			    var box = new google.maps.Polygon({
			            paths: boxCoords,
			            strokeColor: "0000FF",
			            strokeOpacity: 0.2,
			            strokeWeight: 10,
			            fillColor: "#FF0000",
			            fillOpacity: 0 
			        });
			        box.setMap(mapCanvas);
				*/
			  	getReverseGeocodingData(lat, lng);
			}else{
				if(document.getElementById('textSearch') !== null && document.getElementById('textSearch').value !== ''){
					var geocoder = new google.maps.Geocoder();
					geocoder.geocode({'address': document.getElementById('textSearch').value}, function(results, status) {
						if (status == google.maps.GeocoderStatus.OK) {
							lat = results[0].geometry.location.lat();
							lng = results[0].geometry.location.lng();
							var myOptions = {
						      //zoom: 12,
						      scaleControl: true,
						      maxZoom: maxzoom,
						      center: new google.maps.LatLng(lat, lng),
						      mapTypeId: google.maps.MapTypeId.ROADMAP
						    }
							var mapDiv = document.getElementById("map_canvas");
							var mapCanvas = new google.maps.Map(mapDiv, myOptions);
							var bounds = new google.maps.LatLngBounds(
								new google.maps.LatLng(lat, lng),
								new google.maps.LatLng(lat, lng));		    
						  	mapCanvas.fitBounds(bounds);
						}
					});
				}else{
			  		var myOptions = {
				      //zoom: 12,
				      scaleControl: true,
				      maxZoom: maxzoom,
				      center: new google.maps.LatLng(lat, lng),
				      mapTypeId: google.maps.MapTypeId.ROADMAP
				    }
					var mapDiv = document.getElementById("map_canvas");
					var mapCanvas = new google.maps.Map(mapDiv, myOptions);
					var bounds = new google.maps.LatLngBounds(
						new google.maps.LatLng(lat, lng),
						new google.maps.LatLng(lat, lng));		    
				  	mapCanvas.fitBounds(bounds);
				}
				document.getElementById('list-items').style.display = 'none';
		  	}
	  	}
	}
	
	xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
	xmlhttp.send('minLat=' + min_lat + '&maxLat=' + max_lat + '&minLng=' + min_lng + '&maxLng=' + max_lng);
}
function createMarker(map, latlng, title, description, photo, date,address) {
  //Creates a marker
  var marker = new google.maps.Marker({
    position : latlng,
    map : map,
    title : title,
    desc: description,
    photo: photo,
    date: date,
    address: address,
    icon: '/themes/default/frontend/images/icon-address.png'
  });
  
  //The infoWindow is opened when the sidebar button is clicked
  google.maps.event.addListener(marker, "click", function(){
  	var html = '<div class="item"><div class="head-item">' +
					'<div class="image-item">' +
						'<img src="/images/post/'+photo+'">' +
					'</div>' +
					'<div class="title-item">' +
						'<a href="javascript:void(0);">'+title+'</a>' +
					'</div>' +
				'</div>' +
				'<div class="content-item">' +
					'<p class="address-item">' +address + '</p>' +
					'<p class="calendar-item">' +date + ' - ' + marker.end_date +'</p>' +
					'<p>' + description + '</p>' +
				'</div></div>';
    infoWnd.setContent(html);
    infoWnd.open(map, marker);
  });
  return marker;
}
function createMarkerButton(marker) {
  //Creates a sidebar button
  	var div = document.getElementById("items");
	var li = document.createElement("li");
  	var html = '<div class="head-item">' +
					'<div class="left-item">' +
						'<img src="/images/post/'+marker.photo+'">' +
					'</div>' +
					'<div class="right-item">' +
						'<a href="javascript:void(0);">' + marker.getTitle() + '</a>' +
						'<p class="address-item">' + marker.address + '</p>' +
						'<p class="calendar-item">' + marker.date + ' - ' + marker.end_date +'</p>' +
					'</div>' +
				'</div>' +
				'<div class="content-item">' +
						'<p>' + marker.desc + '</p>' +
				'</div>';
  	li.innerHTML = html;
  	li.setAttribute('class','item-view');
  	div.appendChild(li)
  
  //Trigger a click event to marker when the button is clicked.
  google.maps.event.addDomListener(li, "click", function(){
    google.maps.event.trigger(marker, "click");
  });
}